package com.meisiabc.app.service;

import com.meisiabc.support.cache.SmsCodeCache;
import com.meisiabc.support.sms.SmsClient;
import com.meisiabc.utils.MobileUtils;
import com.meisiabc.utils.StringFormat;
import com.meisiabc.utils.Verify;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class SmsCodeService {
    public static final String PROFILE = "PROFILE";
    public static final String FREE_AUDITION = "FREE_AUDITION";
    public static final String MODIFY = "MODIFY";
    public static final String WECHAT_MP = "WECHAT_MP";

    private static final String SMS_TEMPLATE = "您的验证码是：{}。请不要把验证码泄露给其他人。";

    @Autowired
    private SmsCodeCache smsCodeCache;

    @Autowired
    private SmsClient smsClient;

    public void sendSms(String prefix, String mobile) {
        Verify.isTrue(MobileUtils.isValidMobile(mobile), "请输入合法的手机号码");
        Verify.isTrue(smsCodeCache.getCode(prefix, mobile) == null, "发送验证码太频繁，请稍后再试");

        String code = smsCodeCache.generateSmsCode();
        smsCodeCache.put(prefix, mobile, code);

        if (smsClient.sendSms(mobile, StringFormat.format(SMS_TEMPLATE, code))) {
            log.info("send sms success.[prefix={},mobile={},code={}]", prefix, mobile, code);
        } else {
            log.info("send sms error.[prefix={},mobile={},code={}]", prefix, mobile, code);
        }
    }

    public boolean verifySmsCode(String prefix, String mobile, String smsCode) {
        Verify.isTrue(MobileUtils.isValidMobile(mobile), "请输入合法的手机号码");
        Verify.isTrue(MobileUtils.isValidSmsCode(smsCode), "请输入合法的短信验证码");

        String targetCode = smsCodeCache.getCode(prefix, mobile);
        Verify.isTrue(smsCode.equals(targetCode), "短信验证码无效");

        smsCodeCache.remove(prefix, mobile);
        return true;
    }
}
